﻿using System.Collections;
using DataServer.ApplicationLib.Entities;
using DataServer.ApplicationLib.Repositories;

namespace DataServer.ApplicationLib.Services
{
    public class ReportService : IReportService
    {
        private readonly IReportRepository _reportRepository;

        public ReportService(IReportRepository reportRepository)
        {
            _reportRepository = reportRepository;
        }

        // public async Task<ReportDataInfoResponseDto> SearchData(ReportDataSearchRequestDto request)
        // {
        //     var searchDataParam = CreateSearchDataParam(request);
        //
        //     var reportFields = _reportRepository.GetReportFieldByReportId(request.ReportId);
        //     if (reportFields != null && reportFields.Any())
        //     {
        //         var queryArgDsDTOS = CreateQueryArgDsDto(reportFields, searchDataParam.FilterValues);
        //         var displayNames = CreateDisplayNames(reportFields, searchDataParam.SelectedFieldNames);
        //         var groupBy = CreateGroupBy(reportFields);
        //
        //         // 查询数据服务
        //     }
        //
        //     return base.SearchData(request, context);
        // }

        private IList<string> CreateGroupBy(IList<ReportFieldEntity> reportFields)
        {
            if (reportFields != null && reportFields.Any())
            {
                if (reportFields.Any(i => i.IsGroupBy))
                {
                    return reportFields.Where(i => !i.IsGroupBy).Select(i => i.FieldName).ToList();
                }
                else
                {
                    return new List<string>();
                }
            }
            else
            {
                return new List<string>();
            }
        }

        // protected IList<QueryArgDsDto> CreateQueryArgDsDto(IList<ReportFieldEntity> reportFields,
        //     IDictionary<string, object> filterValues)
        // {
        //     IList<QueryArgDsDto> result = new List<QueryArgDsDto>();
        //
        //     if (filterValues != null && filterValues.Any() && reportFields != null && reportFields.Any())
        //     {
        //         foreach (var reportField in reportFields)
        //         {
        //             if (filterValues.ContainsKey(reportField.FieldName))
        //             {
        //                 var queryArgDsDTO = new QueryArgDsDto
        //                 {
        //                     Name = reportField.FieldName
        //                 };
        //
        //                 //            string dtoValue = this.getQueryArgDsDtoValue(filterValues.get(reportField.getFieldName()), reportField);
        //                 //            super.restDateFormat(reportField, queryArgDsDTO, dtoValue);
        //                 //            queryArgDsDTO.setOperator(ReportFieldSearchLogicOp.valueOf(reportField.getSearchLogicOp()).getOperatorType());
        //
        //                 if (!string.IsNullOrEmpty(queryArgDsDTO.Value))
        //                 {
        //                     result.Add(queryArgDsDTO);
        //                 }
        //             }
        //         }
        //     }
        //
        //
        //     return result;
        // }

        protected string? GetQueryArgDsDtoValue(object value, ReportFieldEntity reportField)
        {
            if (value == null)
            {
                return null;
            }

            if (value is ICollection)
            {
                //Collection valueCollection = (Collection)value;
                //if (valueCollection.size() == 0)
                //{
                //    return null;
                //}
                IList<string> valueStr = new List<string>();
                //valueCollection.stream().forEach(i->valueStr.add(this.getQueryArgDsDtoRealValue(i, reportField)));
                return string.Join(",", valueStr);
            }

            //return GetQueryArgDsDtoRealValue(value, reportField);

            return string.Empty;
        }

        //private string GetQueryArgDsDtoRealValue(object value, ReportFieldEntity reportField)
        //{
        //    if (this.isFilterByDate(reportField))
        //    {
        //        return ParseDateValue(string.ValueOf(value), ReportFieldDataType.valueOf(reportField.DataType.ToUpper()));
        //    }
        //    else
        //    {
        //        return String.valueOf(value);
        //    }
        //}

        //private bool IsFilterByDate(ReportFieldEntity reportField)
        //{
        //    if (!string.IsNullOrEmpty(reportField.getSearchInputType()))
        //    {
        //        return ReportFieldSearchInputType.valueOf(reportField.getSearchInputType()).isDateType();
        //    }
        //    else
        //    {
        //        ReportFieldDataType dataType = ReportFieldDataType.valueOf(reportField.getDataType().toUpperCase());
        //        return dataType.equals(ReportFieldDataType.DATE);
        //    }
        //}

        //private String ParseDateValue(String value, ReportFieldDataType reportFieldDataType)
        //{
        //    switch (reportFieldDataType)
        //    {
        //        case NUMBER:
        //            return String.valueOf(Integer.parseInt(value.replace("-", "")));
        //        default:
        //            return value;
        //    }
        //}

        private IDictionary<string, string> CreateDisplayNames(IList<ReportFieldEntity> reportFields,
            IList<string> selectedFieldNames)
        {
            IDictionary<string, string> result = new Dictionary<string, string>();
            if (reportFields != null && reportFields.Any())
            {
                foreach (ReportFieldEntity reportField in reportFields)
                {
                    if (selectedFieldNames.Any(i => i.Equals(reportField.FieldName)))
                    {
                        if (string.IsNullOrEmpty(reportField.SummaryType))
                        {
                            result.Add(reportField.FieldName, reportField.FieldName);
                        }
                        else if (reportField.SummaryType.Equals("COUNT_DISTINCT"))
                        {
                            string formatColumn = string.Format("COUNT(DISTINCT {0})", reportField.FieldName);
                            result.Add(formatColumn, formatColumn.Replace("([\\(\\s\\)]+)", "_"));
                        }
                        else
                        {
                            string formatColumn = string.Format("{0}({1})", reportField.SummaryType, reportField.FieldName);
                            result.Add(formatColumn, formatColumn.Replace("([\\(\\s\\)]+)", "_"));
                        }
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 创建查询数据参数对象
        /// </summary>
        /// <param name="requestDto"></param>
        /// <returns></returns>
        // private SearchDataParam CreateSearchDataParam(ReportDataSearchRequestDto requestDto)
        // {
        //     // if (requestDto == null)
        //     // {
        //     //     throw new ArgumentNullException("SearchReportDataRequestDto Param Is Null");
        //     // }
        //     //
        //     // var report = _reportRepository.GetReport(requestDto.ReportId);
        //     //
        //     // if (report == null)
        //     // {
        //     //     throw new ArgumentNullException("report not found: " + requestDto.ReportId);
        //     // }
        //
        //     //UserRightParam userRightParam = new UserRightParam(requestDto.getUserId(), requestDto.getRoleId(), report.isRoleBased(), application.getJarvisAppId());
        //     // SearchDataPage searchDataPage = requestDto.Pager != null
        //     //     ? new SearchDataPage(requestDto.Pager.PageIndex, requestDto.Pager.PageSize)
        //     //     : null;
        //     // SearchDataSort searchDataSort = requestDto.Sorting != null
        //     //     ? new SearchDataSort(requestDto.Sorting.FieldName, requestDto.Sorting.Order)
        //     //     : null;
        //     //
        //     // SearchDataParam searchDataParam = new SearchDataParam(
        //     //     report,
        //     //     requestDto.SelectedFieldNames.ToList<string>(),
        //     //     DeserializeFilterValues(requestDto.FilterValuesJson),
        //     //     searchDataPage,
        //     //     searchDataSort
        //     // );
        //
        //     return searchDataParam;
        // }

        private IDictionary<string, object> DeserializeFilterValues(string filterValuesJson)
        {
            throw new NotImplementedException();
        }
    }
}